package com.hao.utils.web;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hao.utils.modal.DataModal;
import com.hao.utils.modal.DataModalColumnDefine;

@RestController
@RequestMapping("/datas")
public class DatasController {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@PostMapping("csv")
	public Map<String,Object> generateCsvDatasFiles(@RequestBody DataModal dataModal) throws Exception {
		Map<String,Object> result = new HashMap<>();
		File dataFile = new File(dataModal.getFileName() + ".csv");
		result.put("fileName", dataFile.getPath());
		result.put("AbsolutePath", dataFile.getAbsolutePath());
		logger.debug("filePath:{}", dataFile.getPath());
		FileUtils.deleteQuietly(dataFile);
		
		int step = 1000;
		for (int j = 0; j < dataModal.getSize(); j = j + step) {
			int innerLoop = (dataModal.getSize() - step) >= 0 ? step : (dataModal.getSize() - step);
			List<String> lines = new ArrayList<String>(1000);
			for (int i = 0; i < innerLoop; i++) {
				List<String> line = new ArrayList<String>();
				for (DataModalColumnDefine de : dataModal.getColumnDefines()) {
					line.add(handerColumnValue(de));
				}
				String lineTmp = StringUtils.join(line, ",");
				lines.add(lineTmp);
			}
			FileUtils.writeLines(dataFile, "UTF-8", lines, null, true);
		}
		return result;
	}

	private String handerColumnValue(DataModalColumnDefine de) {
		String tmp = "";
		switch (de.getType()) {
		case "string":
			tmp = de.getDefaultValue();
			if (StringUtils.isBlank(tmp)) {
				tmp = RandomStringUtils.randomAlphabetic(de.getLength());
			}
			break;
		case "double":
			tmp = de.getDefaultValue();
			if (StringUtils.isBlank(tmp)) {
				tmp = String.format("%."+de.getLength()+"f", RandomUtils.nextDouble());
			}
			break;
		case "float":
			tmp = de.getDefaultValue();
			if (StringUtils.isBlank(tmp)) {
				tmp = String.format("%."+de.getLength()+"f", RandomUtils.nextFloat());
			}
			break;
		case "long":
		case "int":
			tmp = de.getDefaultValue();
			if (StringUtils.isBlank(tmp)) {
				tmp = RandomStringUtils.randomNumeric(de.getLength(), de.getLength());
			}
			break;
		default:
			break;
		}
		return tmp;
	}
}
